Max Points on a Line || Guess Number Higher or Lower II

Max Points on a Line

Question

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

Analysis

九章算法

  • map.put((double)Integer.MIN_VALUE,1); 可能整个序列都是相同点,他们的斜率用MIN_VALUE表示
  • 利用dup变量记录有多少个重复的点
  • 每次进入一个新的坐标点比较的时候记住map.clear
  • 计算key的时候必须+0.0,否则无法通过所有点纵坐标相同的情况

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/
public class Solution {
public int maxPoints(Point[] points) {
if(points.length<2)
return points.length;
Map<Double,Integer> map=new HashMap<Double,Integer>();
int max=1;
for(int i=0;i<points.length;i++){
map.clear();
map.put((double)Integer.MAX_VALUE,1);
int dup=0;
for(int j=i+1;j<points.length;j++){
double key=0;
if(points[i].x==points[j].x&&points[i].y==points[j].y){
dup++;
continue;
}
if(points[i].x==points[j].x)
key=(double)Integer.MAX_VALUE;
else
key=0.0+(double)(points[i].y-points[j].y)/(double)(points[i].x-points[j].x);
map.put(key,map.getOrDefault(key,1)+1);
}
for(int tmp:map.values()){
max=Math.max(dup+tmp,max);
}
}
return max;
}
}

Palindrome Partitioning II

Question

We are playing the Guess Game. The game is as follows:

I pick a number from 1 to n. You have to guess which number I picked.

Every time you guess wrong, I’ll tell you whether the number I picked is higher or lower.

However, when you guess a particular number x, and you guess wrong, you pay $x. You win the game when you guess the number I picked.

Example:

1
2
3
4
5
6
n = 10, I pick 8.
First round: You guess 5, I tell you that it's higher. You pay $5.
Second round: You guess 7, I tell you that it's higher. You pay $7.
Third round: You guess 9, I tell you that it's lower. You pay $9.
Game over. 8 is the number I picked.
You end up paying $5 + $7 + $9 = $21.

Given a particular n ≥ 1, find out how much money you need to have to guarantee a win.

Analysis

中文参考

LeetCode Discuss

最大最小化

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Solution {
public int getMoneyAmount(int n) {
int[][] table = new int[n+1][n+1];
return DP(table, 1, n);
}
int DP(int[][] t, int s, int e){
if(s >= e) return 0;
if(t[s][e] != 0) return t[s][e];
int res = Integer.MAX_VALUE;
for(int x=s; x<=e; x++){
int tmp = x + Math.max(DP(t, s, x-1), DP(t, x+1, e));
res = Math.min(res, tmp);
}
t[s][e] = res;
return res;
}
}